<template>
  <div class="app-container" :style="windowWidth < 1080 ? 'background-color: #f6f8f9;' : ''">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch"
      :label-width="windowWidth < 1080 ? '100px' : '68px'"
      :style="windowWidth < 1080 ? 'background-color: #fff;padding: 20px 20px 0;' : ''">
      <el-form-item label="充值账号" prop="account">
        <el-input v-model="queryParams.accountName" placeholder="昵称/抖音ID/系统ID/备注" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="所属通道" prop="channelId">
        <el-select v-model="queryParams.channelId" placeholder="请选择所属通道" size="small" clearable>
          <el-option v-for="item in channelList" :key="item.channelId" :label="item.channelName"
            :value="item.channelId" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属分组" prop="groupId">
        <el-select v-model="queryParams.groupId" placeholder="请选择所属分组" @clear="groupClear" size="small" clearable>
          <el-option v-for="item in accountGroupList" :key="item.groupId" :label="item.groupName"
            :value="item.groupId" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属核销" prop="userId">
        <el-cascader v-model="chooseUserArr" :props="writeOffUserProps" :show-all-levels="false" clearable></el-cascader>
      </el-form-item>
      <el-form-item label="账号状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择账号状态" clearable size="small">
          <el-option label="启用" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="错误信息" prop="errorMsg">
        <el-select v-model="queryParams.errorMsg" placeholder="请选择错误信息" clearable size="small">
          <el-option label="违规" value="违规" />
          <el-option label="CK过期" value="CK过期" />
          <el-option label="复活成功" value="复活成功" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" v-if="windowWidth > 1080">
        <el-date-picker v-model="daterangeCreateTime" size="small" style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss" type="daterange" range-separator="-" start-placeholder="开始日期"
          end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置条件</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8"
      :style="windowWidth < 1080 ? 'background-color: #fff;margin:0;padding:0 15px 20px;' : ''">
      <!--       <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['merchant:account:add']">新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="multiple" @click="handleBatchUpdate"
          v-hasPermi="['merchant:account:edit']">批量修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['merchant:account:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-delete" size="mini" :disabled="multiple"
          @click="handleBatchStatusChange(0)" v-hasPermi="['merchant:account:remove']">批量开启</el-button>
      </el-col>
      <el-col :span="1.5" class="delete">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
          @click="handleBatchStatusChange(1)" v-hasPermi="['merchant:account:remove']">批量停用</el-button>
      </el-col>
      <el-col :span="1.5" v-if="windowWidth > 1080">
        <el-button type="primary" plain icon="el-icon-download" size="mini" :loading="exportLoading"
          @click="handleExport">导出</el-button>
      </el-col>
      <el-col :span="1.5" v-if="windowWidth > 1080">
        <el-button type="primary" plain size="mini" :loading="reviveLoading"
          @click="handleRevive">一键复活</el-button>
      </el-col>
      <el-col :span="1.5" v-if="windowWidth > 1080">
        <el-button type="primary" plain size="mini" :loading="importLoading"
                   @click="handelImportAccount">批量导入</el-button>
      </el-col>
      <el-col :span="1.5" v-if="windowWidth > 1080">
        <el-button type="primary" plain size="mini" :loading="importCKLoading"
                   @click="handelImportAccountCK">批量导入修改CK</el-button>
      </el-col>
      <!--       <el-col :span="1.5">
        <el-button type="primary  " plain icon="el-icon-delete" size="mini" @click="handleCheckOfGroup"
          v-hasPermi="['merchant:account:remove']">一键检测【分组】</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"
        :style="windowWidth > 1080 ? '' : 'margin-top:10px;'"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="accountList" @selection-change="handleSelectionChange" ref="tableDateRef">
      <el-table-column type="selection" width="55" align="left" />
      <el-table-column label="账号ID" align="left" prop="accountId" v-if="columns[0].visible" :key="Math.random()" />
      <el-table-column label="头像" align="left" prop="avatar" v-if="columns[1].visible" :key="Math.random()">
        <template slot-scope="scope">
          <el-image style="width:50px;height:50px;" :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]"
            :key="Math.random()" />
        </template>
      </el-table-column>
      <el-table-column label="账号名称" align="left" width="100" prop="accountName" v-if="columns[2].visible"
        :key="Math.random()" />
      <el-table-column label="抖音ID" align="left" width="120" prop="douyinId"
        v-if="columns[3].visible && windowWidth > 1080" :key="Math.random()" />
      <el-table-column label="抖音ID" align="left" width="120" prop="douyinId"
        v-if="columns[3].visible && windowWidth < 1080" :key="Math.random()" fixed="left" />
      <el-table-column label="所属分组" align="left" width="100" prop="groupName" v-if="columns[4].visible"
        :key="Math.random()" />
      <el-table-column label="所属通道" align="left" width="200" prop="channelName" v-if="columns[5].visible"
        :key="Math.random()" />
      <el-table-column label="所属核销" align="left" width="200" prop="userName" v-if="columns[17].visible"
        :key="Math.random()" />
      <el-table-column label="所属地区" align="left" width="200" prop="proxyAreaName" v-if="columns[18].visible"
        :key="Math.random()" />
      <el-table-column label="日限额" align="left" prop="dailyLimitQuota" v-if="columns[6].visible" :key="Math.random()">
        <template slot-scope="scope">
          <span v-if="scope.row.dailyLimitQuota == 0 ">无限制</span>
          <span v-else>{{scope.row.dailyLimitQuota}}</span>
        </template>
      </el-table-column>
      <el-table-column label="总限额" align="left" prop="totalLimitQuota" v-if="columns[7].visible" :key="Math.random()">
        <template slot-scope="scope">
          <span v-if="scope.row.totalLimitQuota == 0 ">无限制</span>
          <span v-else>{{scope.row.totalLimitQuota}}</span>
        </template>
      </el-table-column>
      <el-table-column label="收款限制" align="left" width="150" prop="quota" v-if="columns[8].visible"
        :key="Math.random()">
        <template slot-scope="scope">
          <span v-if="scope.row.cashierNlt == 0 && scope.row.cashierNmt == 0">无限制</span>
          <span v-else>
            <span v-if="scope.row.cashierNlt != 0">{{scope.row.cashierNlt}}</span>
            <span v-else-if="scope.row.cashierNlt ==0">无限制</span>
            -
            <span v-if="scope.row.cashierNmt != 0">{{scope.row.cashierNmt}}</span>
            <span v-else-if="scope.row.cashierNmt ==0">无限制</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="昨日收入" align="left" prop="yesterdayIncome" v-if="columns[9].visible"
        :key="Math.random()" />
      <el-table-column label="今日收入" align="left" prop="todayIncome" v-if="columns[10].visible" :key="Math.random()" />
      <el-table-column label="总收入" align="left" prop="totalIncome" v-if="columns[11].visible" :key="Math.random()" />
      <el-table-column label="日成功订单" width="150" align="left" prop="totalIncome" v-if="columns[12].visible"
        :key="Math.random()">
        <template slot-scope="scope">
          <span>{{scope.row.todayTotalSuccessTrad}} / {{scope.row.todayTotalTrade}}</span>
        </template>
      </el-table-column>
      <el-table-column label="剩余额度" align="left" prop="surplusQuota" v-if="columns[13].visible" :key="Math.random()" />
      <el-table-column label="账号状态" align="left" prop="status" v-if="columns[14].visible" :key="Math.random()">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="失败原因" :show-overflow-tooltip="true" align="left" prop="errorMsg"
        v-if="columns[15].visible" :key="Math.random()" />
      <el-table-column label="备注" align="left" prop="remark" v-if="columns[16].visible" :key="Math.random()" />
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" fixed="right" width="240"
        v-if="windowWidth > 1080">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-coin" @click="handlePayTest(scope.row)"
            v-hasPermi="['merchant:account:remove']">测试</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['merchant:account:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['merchant:account:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleDistribution(scope.row)"
            v-hasPermi="['merchant:account:remove']">分配</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="240" v-else>
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-coin" @click="handlePayTest(scope.row)"
            v-hasPermi="['merchant:account:remove']">测试</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['merchant:account:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['merchant:account:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleDistribution(scope.row)"
            v-hasPermi="['merchant:account:remove']">分配</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" style="height:57px;" />

    <!-- 添加或修改账号信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" :width="isMobile?'90%':'650px'" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="抖音ID" prop="douyinId" v-if="!batchUpdate && channel.isNeedDouYinId == 0">
          <el-input v-model="form.douyinId" placeholder="请输入抖音ID" disabled />
        </el-form-item>
<!--        <el-form-item label="cookie" prop="ck" v-if="!batchUpdate && channel.isNeedCk == 0">-->
<!--          <el-input v-model="form.ck" placeholder="请输入cookie" />-->
<!--        </el-form-item>-->
        <el-form-item label="设备编码" prop="deviceId" v-if="!batchUpdate && channel.isNeedDeviceId == 0">
          <el-input v-model="form.deviceId" placeholder="请输入设备编码" />
        </el-form-item>
        <div v-if="channel.isFixed == 0">
          <el-form-item v-for="(item, index) in form.fixedAmounts" :label="'额度' + (index + 1)" :key="index">
            <!-- :prop="'domains.' + index + '.value'" -->
            <el-row>
              <el-col :span="3">
                <el-input v-model="item.money" placeholder="额度"></el-input>
              </el-col>
              <el-col :span="1" style="text-align:center">
                <span>一</span>
              </el-col>
              <el-col :span="13">
                <el-input v-model="item.payUrl" placeholder="充值链接"></el-input>
              </el-col>
              <el-col :span="3" offset="1">
                <el-button type="primary" plain icon="el-icon-plus" @click="addFixedAmount(index+1)"></el-button>
              </el-col>
              <el-col :span="3" v-if="index != 0">
                <el-button type="danger" plain icon="el-icon-delete" @click="removeFixedAmount(item)">
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </div>
        <el-form-item label="指定代理信息" prop="proxyModel">
          <el-select v-model="form.proxyModel" placeholder="请选择指定代理" size="small">
            <el-option v-for="item in proxyList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <div style="display: inline-block;margin-left: 18px;" v-if="form.proxyModel == 1">
            <el-input v-model="form.proxyHost" placeholder="IP" style="width:200px;" size="small"></el-input>
            <el-input v-model="form.proxyPort" placeholder="端口" style="width:100px;" size="small"></el-input>
          </div>
<!--          <div style="display: inline-block;margin-left: 18px;" v-if="proxyModule == 2">-->
<!--            <el-input v-model="proxyAreaName" placeholder="选择指定区域代理" style="width:200px;" size="small"-->
<!--              @focus="regionDing('')"></el-input>-->
<!--          </div>-->
        </el-form-item>
        <el-form-item label="地区" prop="proxyArea" v-if="form.proxyModel == 2">
          <el-cascader v-model="form.proxyArea" :options="regionList" :props="props" :show-all-levels="false" filterable @change="handleChange"></el-cascader>
        </el-form-item>
        <el-form-item label="所属分组" prop="groupId">
          <el-select v-model="form.groupId" placeholder="请选择所属分组" size="small">
            <el-option v-for="item in accountGroupList" :key="item.groupId" :label="item.groupName"
              :value="item.groupId" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属核销" prop="userId">
          <el-cascader v-model="chooseArr" :props="writeOffProps" :show-all-levels="false"></el-cascader>
        </el-form-item>
        <!-- <el-form-item label="指定代理信息">
          <el-row>
            <el-col :span="20">
              <el-input v-model="form.proxyHost" placeholder="IP"></el-input>
            </el-col>
            <el-col :span="4">
              <el-input v-model="form.proxyPort" placeholder="端口"></el-input>
            </el-col>
          </el-row>
        </el-form-item> -->
        <el-form-item label="日限额" prop="dailyLimitQuota">
          <el-input v-model="form.dailyLimitQuota" placeholder="为空或0则不限制" />
        </el-form-item>
        <el-form-item label="总限额" prop="totalLimitQuota">
          <el-input v-model="form.totalLimitQuota" placeholder="为空或0则不限制" />
        </el-form-item>
        <el-form-item label="收款限制" style="text-align:center">
          <el-row>
            <el-col :span="11">
              <el-input v-model="form.cashierNlt" placeholder="为空或0则不限制" />
            </el-col>
            <el-col :span="2">
              <span>一</span>
            </el-col>
            <el-col :span="11">
              <el-input v-model="form.cashierNmt" placeholder="为空或0则不限制" />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="CK" prop="json" v-if="!batchUpdate && channel.isNeedCk == 0">
          <el-input v-model="form.json" placeholder="请扫码获取json，并填入" />
        </el-form-item>
        <el-form-item label="iId" prop="installId" v-if="!batchUpdate && channel.isNeedDeviceId == 0">
          <el-input v-model="form.installId" placeholder="请输入iid" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <el-dialog :width="isMobile?'90%':'650px'" :close-on-click-modal="false" class="region" :visible.sync="regionDialog" append-to-body>
        <div class="region-head">
          <span style="font-size: 19px;font-weight: bold;">全部地区</span>
          <el-input v-model="regionModule" style="width:200px;margin-left:20px;font-size: 16px;" size="small"
            class="region-input"></el-input>
          <el-button type="primary" @click="handleSearch" size="small"
            style="border-radius: 0;font-size: 16px;height: 32px;">搜索</el-button>
        </div>
        <div style="overflow: auto;height: 500px;">
          <div style="margin-bottom:10px;" v-for="item in regionList" :key="item.label">
            <div style="font-size: 16px;background: #f7f8fb;padding: 10px 20px;text-align: left;margin-bottom:10px;">
              {{item.label}}</div>
            <div class="city-choice">
              <div :class="proxyAreaCode == val.id ? 'city-itme-btn' : 'city-itme'" v-for="val in item.children"
                :key="val.id" @click="handleChoice(val)" @dblclick="handleBd(val)">{{val.label}}</div>
            </div>
          </div>
        </div>
        <div style="height:60px;text-align: center;line-height: 80px;">
          <el-button type="primary" @click="regionDialog = false">确 定</el-button>
        </div>
      </el-dialog>
    </el-dialog>

    <!-- 支付测试弹窗 -->
    <el-dialog title="支付测试" :visible.sync="payTest_dialog.open" :width="isMobile?'90%':'500px'" append-to-body>
      <el-form ref="payTestForm" :model="payTestForm" :rules="payTestrules" label-width="80px">
        <el-form-item label="支付金额" prop="money">
          <el-input v-model="payTestForm.money" placeholder="请输入支付金额" size="small" />
        </el-form-item>
        <el-form-item label="支付方式" prop="payment">
          <el-select v-model="payTestForm.payment" placeholder="请选择支付方式" size="small">
            <el-option label="微信" value="1" />
            <el-option label="支付宝" value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitPayTestForm">确 定</el-button>
        <el-button @click="payTestCancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 支付测试结果展示弹窗 -->
    <el-dialog title="扫码支付" :visible.sync="payResult_dialog.open" :width="isMobile?'90%':'500px'" append-to-body>
      <div style="text-align: center;">
        <el-image :src="payTestResult.qrCode_base64"></el-image>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="payResultCancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="upload.title" :visible.sync="upload.open" :width="isPhone?'90%':'500px'" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
                 :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
                 :on-error="handleFileError" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" v-if="upload.isCk"
                   @click="importTemplateCK">下载模板</el-link>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" v-else
                   @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm" :loading="submitFileFormLoading">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listAccount,
  getAccount,
  delAccount,
  addAccount,
  updateAccount,
  changeAccountStatus,
  batchChangeAccountStatus,
  checkAccountOfGroup,
  batchUpdateAccount,
  areaList,
  listForTest, changeDIdAndIid
} from '@/api/merchant/account'
  import {
    listArea
  } from "@/api/merchant/proxy";

  import {
    listAccountGroup
  } from "@/api/merchant/accountGroup";

  import {
    payTest,
    payQuery,
    testBatch
  } from "@/api/merchant/pay";

  import {
    listChannel
  } from "@/api/merchant/channel"
  import { mapGetters } from 'vuex'
  import { listAllWriteOff } from '@/api/merchant/writeOff'
  import { getToken } from '@/utils/auth'

  export default {
    name: "Account",
    data() {
      let that = this;
      return {
        // 支付测试dialog
        payTest_dialog: {
          open: false
        },
        // 支付测试的结果
        payTestResult: {},
        // 支付测试结果展示dialog
        payResult_dialog: {
          open: false
        },
        // 支付测试表单
        payTestForm: {},
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 复活loading
        reviveLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 账号信息表格数据
        accountList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否为批量修改
        batchUpdate: false,
        // 备注时间范围
        daterangeCreateTime: [],
        //账号分组列表
        accountGroupList: [],
        //通道列表
        channelList: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          account: undefined,
          userId: undefined,
          channelId: undefined,
          groupId: undefined,
          quota: undefined,
          status: undefined,
          createTime: undefined,
          errorMsg: undefined,
          accountName: undefined,
        },
        // 列信息
        columns: [
          {
            key: 0,
            label: `账号ID`,
            visible: true
          },
          {
            key: 1,
            label: `头像`,
            visible: true
          },
          {
            key: 2,
            label: `账号名称`,
            visible: true
          },
          {
            key: 3,
            label: `抖音ID`,
            visible: true
          },
          {
            key: 4,
            label: `所属分组`,
            visible: true
          },
          {
            key: 5,
            label: `所属通道`,
            visible: true
          },
          {
            key: 6,
            label: `日限额`,
            visible: true
          },
          {
            key: 7,
            label: `总限额`,
            visible: true
          },
          {
            key: 8,
            label: `收款限制`,
            visible: true
          },
          {
            key: 9,
            label: `昨日收入`,
            visible: true
          },
          {
            key: 10,
            label: `今日收入`,
            visible: true
          },
          {
            key: 11,
            label: `总收入`,
            visible: true
          },
          {
            key: 12,
            label: `日成功订单`,
            visible: true
          },
          {
            key: 13,
            label: `剩余额度`,
            visible: true
          },
          {
            key: 14,
            label: `账号状态`,
            visible: true
          },
          {
            key: 15,
            label: `失败原因`,
            visible: true
          },
          {
            key: 16,
            label: `备注`,
            visible: true
          },
          {
            key: 17,
            label: `所属核销`,
            visible: true
          },
          {
            key: 18,
            label: `所属地区`,
            visible: true
          },
        ],
        // 表单参数
        form: {
          channel: {
            isNeedDouYinId: '',
            isNeedCk: 1,
            isNeedDeviceId: 1
          },
          json: '',
          proxyModel: 0,
        },
        proxyList: [
          {
            label: '无',
            value: 0
          },
          {
            label: '指定代理',
            value: 1
          },
          {
            label: '指定区域代理',
            value: 2
          },
        ],
        proxyModule: 0,
        regionDialog: false,
        regionList: [],
        proxyArea:'',
        proxyAreaCode:'',
        proxyAreaName:'',
        regionModule:'',
        props: {
          // checkStrictly: true,
          value: 'id',
          label: 'label',
          children: 'children',
        },
        channel: {
          isNeedDouYinId: '',
          isNeedCk: 1,
          isNeedDeviceId: 1
        },
        // 定时器
        timer: null,
        // 表单校验
        rules: {
          douyinId: [{
            required: true,
            message: "抖音ID不能为空",
            trigger: "blur"
          }],
          ck: [{
            required: true,
            message: "cookie不能为空",
            trigger: "blur"
          }],
          deviceId: [{
            required: true,
            message: "设备编号不能为空",
            trigger: "blur"
          }],
          // json: [{
          //   required: true,
          //   message: "请扫码获取CK，并填入",
          //   trigger: "blur"
          // }]
        },
        payTestrules: {
          money: [{
            required: true,
            message: "金额不能为空",
            trigger: "blur"
          }]
        },
        options: [],
        shareScope: [],
        shareScopeEnd: [],
        areaList: [],
        areaCode: '',
        windowWidth: document.documentElement.clientWidth, //实时屏幕宽度
        chooseArr: [],
        writeOffProps: {
          checkStrictly: true,
          lazy: true,
          // leaf: true,
          lazyLoad (node, resolve) {
            const { value } = node;
            listAllWriteOff({userId: value}).then(res => {
              const nodes = res.map(item => {
                return {
                  value: item.userId,
                  label: item.userName,
                  leaf: item.children < 1,
                }
              });
              resolve(nodes)
            })
          }
        },
        chooseUserArr: [],
        writeOffUserProps: {
          checkStrictly: true,
          lazy: true,
          // leaf: true,
          lazyLoad (node, resolve) {
            const { level, value } = node;
            let userId = '';
            if (level == 0) {
              userId = that.queryParams.userId;
            }else {
              userId = value
            }
            listAllWriteOff({userId: userId}).then(res => {
              const nodes = res.map(item => {
                return {
                  value: item.userId,
                  label: item.userName,
                  leaf: item.children < 1,
                }
              });
              resolve(nodes)
            })
          }
        },
        importLoading: false,
        importCKLoading: false,
        //提交导入账号按钮loading
        submitFileFormLoading: false,
        upload: {
          // 是否显示弹出层）
          open: false,
          title: '',
          isCk: false,
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: {
            Authorization: "Bearer " + getToken()
          },
          // 上传的地址
          url: '',
          //通道ID
          channelId: null,
        },
        //上传地址
        uploadUrl: process.env.VUE_APP_BASE_API + "account/importData/",
        //批量导入表单
        importAccountform: {},
      };
    },
    computed: {
      ...mapGetters(['isMobile', 'chooseUserId']),
      isPhone() {
        let info = navigator.userAgent;
        //通过正则表达式的test方法判断是否包含“Mobile”字符串
        let isPhone = /mobile/i.test(info);
        //如果包含“Mobile”（是手机设备）则返回true
        return isPhone;
      }
    },
    watch: {
      'form.proxyModel': {
        handler:  function() {
          if (this.form.proxyModel == 2) {
            this.regionDing('');
          }
        },
        immediate: true
      },
    },
    created() {
      listAccountGroup().then(response => {
        this.accountGroupList = response.rows;
      });
      listChannel(0).then(response => {
        this.channelList = response.data;
      })
    },
    mounted() {
      // this.queryParams.userId = this.chooseUserId;
      if (this.$route.query.userId) {
        this.queryParams.userId = this.$route.query.userId;
      }
      this.getList();
    },
    beforeUpdate() {
      this.$nextTick(() => {
        this.$refs.tableDateRef.doLayout()
      })
    },
    methods: {
      /** 处理账号导入按钮 */
      handelImportAccountCK() {
        let channelId = this.queryParams.channelId;
        if (channelId) {
          this.upload.open = true;
          this.upload.isCk = true;
          this.upload.title = '批量导入修改CK';
          this.upload.channelId = channelId;
          this.upload.url = process.env.VUE_APP_BASE_API + "account/importCk/" + channelId;
        }else {
          this.$modal.msgError('请选择所属通道！');
        }
      },
      /** 处理账号导入修改CK按钮 */
      handelImportAccount() {
        let channelId = this.queryParams.channelId;
        if (channelId) {
          this.upload.open = true;
          this.upload.isCk = false;
          this.upload.title = '批量导入';
          this.upload.channelId = channelId;
          this.upload.url = this.uploadUrl + channelId;
        }else {
          this.$modal.msgError('请选择所属通道！');
        }
      },
      handleFileUploadProgress() {
        this.submitFileFormLoading = true;
        this.upload.isUploading = true;
      },
      //导入账号成功回调
      handleFileSuccess(response, file, fileList) {
        this.submitFileFormLoading = false;
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$modal.msgSuccess(response.msg);
        this.getList();
      },
      //导入账号失败
      handleFileError() {
        this.submitFileFormLoading = false;
      },
      //下载导入模板
      importTemplate() {
        this.$download.excel('account/importTemplate/' + this.upload.channelId);
      },
      //下载导入模板
      importTemplateCK() {
        this.$download.excel('account/importCKTemplate/' + this.upload.channelId);
      },
      //提交账号导入按钮
      submitFileForm() {
        this.$refs.upload.submit();
        this.upload.channelId = undefined;
      },
      /** 查询账号信息列表 */
      getList() {
        this.loading = true;
        this.queryParams.params = {};
        if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
          this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
          this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
        }
        if (this.chooseUserArr.length > 0) {
          this.queryParams.userId = this.chooseUserArr[this.chooseUserArr.length - 1];
        }else {
          // this.queryParams.userId = '';
        }
        console.log(this.queryParams)
        listAccount(this.queryParams).then(response => {
          this.accountList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.proxyModule = 0
        this.proxyAreaCode = ''
        this.proxyAreaName = ''

        this.form = {
          accountId: undefined,
          account: undefined,
          userId: undefined,
          channelId: undefined,
          groupId: undefined,
          quota: undefined,
          status: "0",
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          remark: undefined,
          json: undefined,
          installId: undefined,
          deviceId: undefined,
          dailyLimitQuota: '',
          totalLimitQuota: '',
          cashierNlt: '',
          cashierNmt: '',
          proxyModel: 0,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.daterangeCreateTime = [];
        this.chooseUserArr = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.accountId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加账号信息";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.batchUpdate = false;
        this.loading = true;
        this.reset();
        const accountId = row.accountId || this.ids
        getAccount(accountId).then(response => {
          this.loading = false;
          this.form = Object.assign(this.form, response.data, {json: response.data.token});
          this.proxyModule = response.data.proxyModel
          if (response.data.proxyAreaCode) {
            this.proxyAreaCode = response.data.proxyAreaCode
            this.proxyAreaName = response.data.proxyAreaName
            this.form.proxyArea = [this.proxyAreaCode.substring(0,2)+'0000', this.proxyAreaCode]
          }

          if (response.data.channel) {
            this.channel = response.data.channel
          }

          this.open = true;
          this.title = "修改账号信息";
        });
        this.options = [],
          this.shareScope = [],
          this.shareScopeEnd = [],
          this.areaList = [],
          this.areaCode = ''
      },
      /** 批量修改按钮操作 */
      handleBatchUpdate() {
        this.batchUpdate = true;
        this.open = true;
        this.title = '批量修改账号';
        this.form = {};
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            // this.form.proxyModel = this.proxyModule
            // if (this.form.proxyModel == 2) {
            //   this.form.proxyAreaCode = this.proxyAreaCode
            //   this.form.proxyAreaName = this.proxyAreaName
            // }
            this.buttonLoading = true;
            let opt = Object.assign({}, this.form, {});
            if (this.chooseArr.length) {
              opt.userId = this.chooseArr[this.chooseArr.length - 1];
            }
            if (this.batchUpdate) {
              const accountIds = this.ids;
              batchUpdateAccount(accountIds, opt).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              if (this.form.accountId != null) {
                opt.areaCode = this.areaCode
                updateAccount(opt).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }).finally(() => {
                  this.buttonLoading = false;
                });
              } else {
                addAccount(opt).then(response => {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }).finally(() => {
                  this.buttonLoading = false;
                });
              }
            }
          }
        });
      },
      // 账号状态修改
      handleStatusChange(row) {
        let text = row.status === "0" ? "启用" : "停用";
        this.$modal.confirm('确认要' + text + '该账号吗？').then(function () {
          return changeAccountStatus(row.accountId, row.status);
        }).then(() => {
          this.$modal.msgSuccess(text + "成功");
        }).catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
      },
      // 批量账号状态修改
      handleBatchStatusChange(status) {
        const accountIds = this.ids;
        let text = status === 0 ? "启用" : "停用";
        this.$modal.confirm('确认要批量' + text + '选择的所有账号吗？').then(function () {
          return batchChangeAccountStatus(accountIds, status);
        }).then(() => {
          //this.loading = false;
          this.$modal.msgSuccess(text + "成功");
          this.getList();
        })
      },
      /** 测试按钮操作 */
      handlePayTest(row) {
        this.payTestForm = {};
        this.payTest_dialog.open = true;
        this.payTestForm.accountId = row.accountId;
        this.payTestForm.channelCode = row.channelId;
        this.payTestForm.pid = row.userId;
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const accountIds = row.accountId || this.ids;
        this.$modal.confirm('是否确认删除账号信息编号为"' + accountIds + '"的数据项？').then(() => {
          this.loading = true;
          return delAccount(accountIds);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).finally(() => {
          this.loading = false;
        });
      },
      /** 账号分配did和iid操作 */
      handleDistribution(row) {
        const accountIds = row.accountId || this.ids;
        this.$modal.confirm('是否分配为编号为"' + accountIds + '"的账号分配did和iid？').then(() => {
          this.loading = true;
          return changeDIdAndIid(accountIds);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("操作成功");
        }).finally(() => {
          this.loading = false;
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.$download.excel('account/export', this.queryParams);
      },
      /** 一键复活按钮操作 */
      handleRevive() {
        this.reviveLoading = true;
        testBatch().then((res) => {
          if (res.code == 200) {
            this.reviveLoading = false;
            this.getList();
            this.$msgbox(res.msg, '一键复活');
          }
        });
      },
      /** 提交支付测试 */
      submitPayTestForm() {
        // debugger
        console.log(JSON.stringify(this.payTestForm));
        payTest(this.payTestForm).then(response => {
          console.log(response);
          if (response.code == 200) {
            this.payTestResult = response.data;
            this.payTest_dialog.open = false;
            this.payTestForm = {};
            this.payResult_dialog.open = true;
            let tradeNo = this.payTestResult.tradeNo;
            // this.queryTradeStatus(tradeNo);
          }
        });
      },
      /** 取消支付测试 */
      payTestCancel() {
        this.payTest_dialog.open = false;
        this.payTestForm = {};
      },
      /** 取消支付结果展示弹窗 */
      payResultCancel() {
        this.payResult_dialog.open = false;
        clearInterval(this.timer);
      },
      queryTradeStatus(tradeNo) {
        const that = this;
        this.timer = setInterval(function () {
          payQuery(tradeNo).then(response => {
            if (that.payResult_dialog.open == false) {
              that.payResultCancel();
            }
            var tradeResult = response.data.tradeResult;
            if (tradeResult == "0") {
              //支付成功
              that.$modal.msgSuccess("支付成功");
              that.payResultCancel();
            } else if (tradeResult == "2") {
              //超时
              that.$modal.msgSuccess("订单已超时");
              that.payResultCancel();
            }
          }).finally(() => {
            that.payResultCancel();
          });
        }, 3000);
      },
      groupClear() {
        this.queryParams.groupId = undefined;
      },
      /** 处理一键检测按钮操作 */
      handleCheckOfGroup() {
        let groupId = this.queryParams.groupId;
        console.log("groupbyID", groupId);
        if (!groupId && groupId != 0) {
          this.$modal.msgError("请先选择一个分组");
        } else {
          this.$modal.confirm('是否确认要一次性检测该分组下的所有账号？').then(() => {
            this.$modal.loading("检测中，请勿刷新页面......");
            checkAccountOfGroup(groupId).then(response => {
              this.$modal.msgSuccess(response.msg);
              this.getList();
            }).finally(() => {
              this.$modal.closeLoading();
            });
          });
        }
      },
      //清除代理区域
      clearProxyArear() {
        this.form.areaCode = '';
        this.areaCode = '';
      },
      //新增固额表单
      addFixedAmount(index) {
        this.form.fixedAmounts.push({
          amount: '',
          payUrl: '',
        })
      },
      removeFixedAmount(item) {
        var index = this.form.fixedAmounts.indexOf(item)
        if (index !== -1) {
          this.form.fixedAmounts.splice(index, 1)
        }
      },
      handleChange(val) {
        console.log(val, '11')
        if (val.length) {
          this.form.proxyAreaCode = val[val.length - 1];
        }else {
          this.form.proxyAreaCode = '';
        }
      },
      //获取地区
      regionDing(data) {
        if (!data) {
          // this.regionDialog = true
          this.proxyAreaCode = ''
          this.proxyAreaName = ''
          this.regionModule = ''
        }
        areaList(data).then(res => {
          this.regionList = res.data
        });
      },
      //地区搜索
      handleSearch() {
        this.regionDing(this.regionModule)
      },
      //选中地区
      handleChoice(data) {
        this.proxyAreaCode = data.id,
          this.proxyAreaName = data.label
      },
      handleBd(data) {
        this.regionDialog = false
        this.proxyAreaCode = data.id,
          this.proxyAreaName = data.label
      }
    }
  };

</script>
<style scoped>
  @media screen and (max-width:475px) {
    .delete {
      margin-top: 10px;
    }
  }

  ::v-deep .el-checkbox__inner {
    width: 20px;
    height: 20px;
  }

  ::v-deep .el-checkbox__inner::after {
    top: 2px;
    height: 10px;
    left: 7px;
  }

  .region ::v-deep .el-dialog__body {
    padding-top: 0;
  }

  .region-head {
    padding-bottom: 20px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }

  .region-input ::v-deep .el-input__inner {
    border: 1px solid #1890ff !important;
    border-radius: 0 !important;
  }

  .city-choice {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
  }

  .city-itme {
    border: 1px solid #dddddd;
    padding: 5px 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 15px;
    cursor: pointer;
    float: left;
    margin: 10px 0;
    margin-right: 10px;
  }

  .city-itme-btn {
    padding: 5px 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 15px;
    cursor: pointer;
    float: left;
    margin: 10px 0;
    margin-right: 10px;
    border: 1px solid #2f55d4;
    background: #eaf1ff;
  }

</style>
